<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>我的 - 农业服务平台</title>
    
    <!-- Favicon -->
    <link rel="icon" type="image/x-icon" href="../favicon.ico">
    <link rel="icon" type="image/png" href="../images/logo.png">
    
    <script src="../js/tailwindcss-3.4.17.js"></script>
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#10b981',
                        'primary-dark': '#059669',
                        secondary: '#06b6d4',
                        accent: '#f59e0b',
                        danger: '#ef4444',
                        neutral: '#f9fafb',
                        'text-primary': '#1f2937',
                        'text-secondary': '#6b7280'
                    }
                }
            }
        }
    </script>
    
    <link rel="stylesheet" href="../css/all.min.css">
    <link rel="stylesheet" href="../css/common.css">
    
    <style>
        /* 商户认证表单样式优化 */
        #merchant-auth-modal .select-wrapper {
            position: relative;
        }
        
        #merchant-auth-modal select {
            background-image: none;
            -webkit-appearance: none;
            -moz-appearance: none;
            appearance: none;
        }
        
        #merchant-auth-modal select:focus {
            box-shadow: 0 0 0 2px rgba(16, 185, 129, 0.2);
            border-color: #10b981;
        }
        
        #merchant-auth-modal select:hover {
            border-color: #d1d5db;
        }
        
        /* 下拉箭头样式 */
        #merchant-auth-modal .select-arrow {
            position: absolute;
            right: 12px;
            top: 50%;
            transform: translateY(-50%);
            pointer-events: none;
            transition: transform 0.2s ease;
        }
        
        #merchant-auth-modal select:focus + .select-arrow {
            transform: translateY(-50%) rotate(180deg);
        }
        
        /* 表单字段间距优化 */
        #merchant-auth-form .form-field {
            margin-bottom: 12px;
        }
        
        /* 输入框聚焦效果 */
        #merchant-auth-form input:focus,
        #merchant-auth-form select:focus {
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(16, 185, 129, 0.15);
        }
        
        /* 按钮样式优化 */
        #send-sms-btn:disabled {
            background-color: #9ca3af;
            cursor: not-allowed;
        }
        
        #send-sms-btn:disabled:hover {
            background-color: #9ca3af;
        }
    </style>
</head>
<body class="bg-gradient-to-br from-slate-50 via-gray-50 to-neutral">
    <div class="container-app">
        <!-- 全新头部设计 - 简约现代风格 -->
        <header class="bg-white border-b border-gray-100">
            <div class="px-4 py-4">
                <!-- 顶部操作栏 -->
                <div class="flex items-center justify-between mb-4">
                    <h1 class="text-lg font-bold text-text-primary">我的</h1>
                    <div class="flex items-center gap-3">
                        <button onclick="requireLogin(() => window.location.href='messages.html', '消息通知')()" class="relative w-9 h-9 rounded-xl hover:bg-gray-100 flex items-center justify-center transition-colors">
                            <i class="fa fa-bell text-text-primary text-lg"></i>
                            <span class="absolute top-1 right-1 w-2 h-2 bg-danger rounded-full"></span>
                        </button>
                        <button onclick="window.location.href='../index.html'" class="w-9 h-9 rounded-xl hover:bg-gray-100 flex items-center justify-center transition-colors">
                            <i class="fa fa-cog text-text-primary text-lg"></i>
                        </button>
                    </div>
                </div>
                
                <!-- 个人信息卡片 -->
                <div class="card-modern p-4">
                    <div class="flex items-center gap-4">
                        <div class="relative">
                            <img id="user-avatar" src="/images/avatar.jpg" 
                                 alt="用户头像" class="w-16 h-16 rounded-2xl cursor-pointer"
                                 onclick="handleAvatarClick()">
                            <div class="absolute -bottom-1 -right-1 w-6 h-6 bg-primary rounded-full flex items-center justify-center shadow-medium">
                                <i class="fa fa-camera text-white text-xs"></i>
                            </div>
                        </div>
                        <div class="flex-1">
                            <h3 class="text-base font-bold text-text-primary mb-1">未登录</h3>
                            <p class="text-xs text-text-secondary mb-2">完善资料获取更多服务</p>
                            <button onclick="window.location.href='login.html'" class="px-4 py-1.5 gradient-primary text-white rounded-lg text-xs font-medium shadow-soft hover:opacity-90 transition-opacity">
                                立即登录
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </header>

        <main class="pb-20">
            <!-- 数据统计卡片 -->
            <div class="px-4 py-4">
                <div class="card-modern p-4">
                    <div class="grid grid-cols-3 divide-x divide-gray-100">
                        <button onclick="handleMyServices()" class="flex flex-col items-center py-2 hover:bg-primary/5 transition-colors rounded-lg">
                            <div class="text-xl font-bold text-primary mb-1">0</div>
                            <div class="text-xs text-text-secondary">我发布的服务</div>
                        </button>
                        <button onclick="handleMyDemands()" class="flex flex-col items-center py-2 hover:bg-primary/5 transition-colors rounded-lg">
                            <div class="text-xl font-bold text-primary mb-1">0</div>
                            <div class="text-xs text-text-secondary">我发布的需求</div>
                        </button>
                        <button onclick="requireLogin(() => window.location.href='my-favorites.html', '我的收藏')()" class="flex flex-col items-center py-2 hover:bg-primary/5 transition-colors rounded-lg">
                            <div class="text-xl font-bold text-primary mb-1">0</div>
                            <div class="text-xs text-text-secondary">我的收藏</div>
                        </button>
                    </div>
                </div>
            </div>
            
            <!-- 账户与安全 -->
            <section class="px-4 mb-4">
                <h2 class="text-base font-bold text-text-primary mb-3 flex items-center">
                    <span class="w-1 h-4 bg-primary rounded-full mr-2"></span>
                    账户与安全
                </h2>
                <div class="card-modern overflow-hidden">
                    <button onclick="requireLogin(() => window.location.href='profile.html', '个人资料')()" class="w-full p-4 flex items-center justify-between hover:bg-primary/5 transition-colors">
                        <div class="flex items-center gap-3">
                            <div class="w-10 h-10 rounded-xl bg-primary/10 flex items-center justify-center">
                                <i class="fa fa-user text-primary"></i>
                            </div>
                            <div class="text-left">
                                <div class="text-sm font-medium text-text-primary">个人资料</div>
                                <div class="text-xs text-text-secondary">完善资料获取更多服务</div>
                            </div>
                        </div>
                        <i class="fa fa-angle-right text-gray-400"></i>
                    </button>
                    
                    <div class="border-t border-gray-100"></div>
                    
                    <button onclick="handleMerchantAuth()" class="w-full p-4 flex items-center justify-between hover:bg-primary/5 transition-colors">
                        <div class="flex items-center gap-3">
                            <div class="w-10 h-10 rounded-xl bg-primary/10 flex items-center justify-center">
                                <i class="fa fa-store text-primary"></i>
                            </div>
                            <div class="text-left">
                                <div class="text-sm font-medium text-text-primary">商户认证</div>
                                <div class="text-xs text-text-secondary" id="merchant-auth-status">未认证</div>
                            </div>
                        </div>
                        <div class="flex items-center gap-2">
                            <span id="merchant-auth-badge" class="text-xs px-2 py-1 bg-gray-100 text-gray-600 rounded-full">未认证</span>
                            <i class="fa fa-angle-right text-gray-400"></i>
                        </div>
                    </button>
                </div>
            </section>
            
            <!-- 帮助中心 -->
            <section class="px-4 mb-4">
                <h2 class="text-base font-bold text-text-primary mb-3 flex items-center">
                    <span class="w-1 h-4 bg-primary rounded-full mr-2"></span>
                    帮助中心
                </h2>
                <div class="card-modern overflow-hidden">
                    <button class="w-full p-4 flex items-center justify-between hover:bg-primary/5 transition-colors">
                        <div class="flex items-center gap-3">
                            <i class="fa fa-question-circle text-secondary text-xl"></i>
                            <span class="text-sm text-text-primary">使用帮助</span>
                        </div>
                        <i class="fa fa-angle-right text-gray-400"></i>
                    </button>
                    
                    <div class="border-t border-gray-100"></div>
                    
                    <button class="w-full p-4 flex items-center justify-between hover:bg-primary/5 transition-colors">
                        <div class="flex items-center gap-3">
                            <i class="fa fa-phone text-secondary text-xl"></i>
                            <span class="text-sm text-text-primary">联系客服</span>
                        </div>
                        <i class="fa fa-angle-right text-gray-400"></i>
                    </button>
                    
                    <div class="border-t border-gray-100"></div>
                    
                    <button class="w-full p-4 flex items-center justify-between hover:bg-primary/5 transition-colors">
                        <div class="flex items-center gap-3">
                            <i class="fa fa-info-circle text-secondary text-xl"></i>
                            <span class="text-sm text-text-primary">关于我们</span>
                        </div>
                        <i class="fa fa-angle-right text-gray-400"></i>
                    </button>
                </div>
            </section>
        </main>
        
        <!-- 退出登录按钮 -->
        <div class="px-4 pb-20">
            <button id="logout-button" onclick="handleLogout()" class="w-full p-4 flex items-center justify-center bg-white rounded-2xl shadow-soft border border-gray-100 hover:shadow-medium transition-all hover:bg-danger/5" style="display: none;">
                <div class="flex items-center gap-3">
                    <div class="w-10 h-10 rounded-xl bg-danger/10 flex items-center justify-center">
                        <i class="fa fa-sign-out text-danger"></i>
                    </div>
                    <div class="text-left">
                        <div class="text-sm font-medium text-danger">退出登录</div>
                        <div class="text-xs text-text-secondary">安全退出当前账号</div>
                    </div>
                </div>
            </button>
        </div>
        
        <!-- 底部导航 -->
        <div id="bottom-nav"></div>
        <div id="publish-modal-container"></div>
        
        <!-- 退出登录确认弹窗 -->
        <div id="logout-modal" class="fixed inset-0 bg-black bg-opacity-50 z-50 hidden flex items-center justify-center p-4">
            <div class="bg-white rounded-2xl shadow-2xl max-w-sm w-full mx-4 transform transition-all duration-300 scale-95 opacity-0" id="logout-modal-content">
                <div class="p-6">
                    <!-- 弹窗头部 -->
                    <div class="flex items-center justify-center mb-4">
                        <div class="w-16 h-16 rounded-full bg-danger/10 flex items-center justify-center">
                            <i class="fa fa-sign-out text-danger text-2xl"></i>
                        </div>
                    </div>
                    
                    <!-- 弹窗内容 -->
                    <div class="text-center mb-6">
                        <h3 class="text-lg font-bold text-text-primary mb-2">确认退出登录</h3>
                        <p class="text-sm text-text-secondary leading-relaxed">
                            退出后需要重新登录才能使用完整功能，确定要退出当前账号吗？
                        </p>
                    </div>
                    
                    <!-- 弹窗按钮 -->
                    <div class="flex gap-3">
                        <button onclick="hideLogoutModal()" 
                                class="flex-1 px-4 py-3 bg-gray-100 text-text-primary rounded-xl font-medium hover:bg-gray-200 transition-colors">
                            取消
                        </button>
                        <button onclick="confirmLogout()" 
                                class="flex-1 px-4 py-3 bg-danger text-white rounded-xl font-medium hover:bg-red-600 transition-colors">
                            确认退出
                        </button>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 头像上传弹窗 -->
        <div id="avatar-upload-modal" class="fixed inset-0 bg-black bg-opacity-50 z-50 hidden flex items-center justify-center p-4">
            <div class="bg-white rounded-2xl shadow-2xl max-w-md w-full mx-4 transform transition-all duration-300 scale-95 opacity-0" id="avatar-upload-modal-content">
                <div class="p-6">
                    <!-- 弹窗头部 -->
                    <div class="flex items-center justify-between mb-4">
                        <h3 class="text-lg font-bold text-text-primary">更换头像</h3>
                        <button onclick="hideAvatarUploadModal()" class="w-8 h-8 rounded-full hover:bg-gray-100 flex items-center justify-center transition-colors">
                            <i class="fa fa-times text-gray-400"></i>
                        </button>
                    </div>
                    
                    <!-- 头像预览区域 -->
                    <div class="flex flex-col items-center mb-6">
                        <div class="relative mb-4">
                            <img id="avatar-preview" src="" alt="头像预览" class="w-24 h-24 rounded-2xl object-cover border-2 border-gray-200">
                            <div class="absolute inset-0 rounded-2xl bg-black bg-opacity-0 hover:bg-opacity-20 transition-all duration-200 flex items-center justify-center">
                                <i class="fa fa-camera text-white text-xl opacity-0 hover:opacity-100 transition-opacity"></i>
                            </div>
                        </div>
                        
                        <!-- 文件选择按钮 -->
                        <input type="file" id="avatar-file-input" accept="image/*" class="hidden" onchange="handleAvatarFileSelect(event)">
                        <button onclick="document.getElementById('avatar-file-input').click()" 
                                class="px-6 py-2 bg-primary text-white rounded-xl font-medium hover:bg-primary-dark transition-colors">
                            选择图片
                        </button>
                        
                        <p class="text-xs text-text-secondary mt-2">支持 JPG、PNG 格式，建议尺寸 200x200 像素</p>
                    </div>
                    
                    <!-- 弹窗按钮 -->
                    <div class="flex gap-3">
                        <button onclick="hideAvatarUploadModal()" 
                                class="flex-1 px-4 py-3 bg-gray-100 text-text-primary rounded-xl font-medium hover:bg-gray-200 transition-colors">
                            取消
                        </button>
                        <button id="save-avatar-btn" onclick="saveAvatar()" 
                                class="flex-1 px-4 py-3 bg-primary text-white rounded-xl font-medium hover:bg-primary-dark transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                                disabled>
                            保存头像
                        </button>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 商户认证弹窗 -->
        <div id="merchant-auth-modal" class="fixed inset-0 bg-black bg-opacity-50 z-50 hidden flex items-center justify-center p-4">
            <div class="bg-white rounded-2xl shadow-2xl max-w-md w-full mx-4 transform transition-all duration-300 scale-95 opacity-0" id="merchant-auth-modal-content">
                <div class="p-6 max-h-[80vh] overflow-y-auto">
                    <!-- 弹窗头部 -->
                    <div class="flex items-center justify-between mb-4">
                        <h3 class="text-lg font-bold text-text-primary">商户认证</h3>
                        <button onclick="hideMerchantAuthModal()" class="w-8 h-8 rounded-full hover:bg-gray-100 flex items-center justify-center transition-colors">
                            <i class="fa fa-times text-gray-400"></i>
                        </button>
                    </div>
                    
                    <!-- 认证状态提示 -->
                    <div id="auth-status-info" class="mb-4 p-3 bg-blue-50 rounded-xl border border-blue-200">
                        <div class="flex items-center gap-2">
                            <i class="fa fa-info-circle text-blue-600"></i>
                            <p class="text-sm text-blue-800">请填写真实的商户信息，我们将进行审核</p>
                        </div>
                    </div>
                    
                    <!-- 认证表单 -->
                    <form id="merchant-auth-form" class="space-y-3">
                        <!-- 商户类型 -->
                        <div>
                            <label class="block text-sm font-medium text-text-primary mb-2">
                                商户类型 <span class="text-red-500">*</span>
                                <span class="text-xs text-text-secondary font-normal ml-1">(可多选)</span>
                            </label>
                            <div id="merchant-type-container" class="grid grid-cols-2 gap-2 max-h-48 overflow-y-auto p-2 border border-gray-200 rounded-lg bg-white">
                                <!-- 复选框将通过JavaScript从shfl字典动态加载 -->
                                <p class="col-span-2 text-xs text-text-secondary text-center py-2">加载中...</p>
                            </div>
                            <p class="text-xs text-text-secondary mt-1">请至少选择一个商户类型</p>
                        </div>
                        
                        <!-- 商户名称 -->
                        <div>
                            <label class="block text-sm font-medium text-text-primary mb-1.5">
                                商户名称 <span class="text-red-500">*</span>
                            </label>
                            <input type="text" id="merchant-name" name="merchantName" required
                                   class="w-full px-3 py-2.5 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary transition-all"
                                   placeholder="请输入商户全称">
                        </div>
                        
                        <!-- 统一社会信用代码 -->
                        <div>
                            <label class="block text-sm font-medium text-text-primary mb-1.5">
                                统一社会信用代码 <span class="text-red-500">*</span>
                            </label>
                            <input type="text" id="credit-code" name="creditCode" required
                                   class="w-full px-3 py-2.5 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary transition-all"
                                   placeholder="请输入18位统一社会信用代码" maxlength="18">
                            <p class="text-xs text-text-secondary mt-1">请填写营业执照上的18位统一社会信用代码</p>
                        </div>
                        
                        <!-- 联系人 -->
                        <div>
                            <label class="block text-sm font-medium text-text-primary mb-1.5">
                                联系人 <span class="text-red-500">*</span>
                            </label>
                            <input type="text" id="contact-person" name="contactPerson" required
                                   class="w-full px-3 py-2.5 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary transition-all"
                                   placeholder="请输入联系人姓名">
                        </div>
                        
                        <!-- 联系电话 -->
                        <div>
                            <label class="block text-sm font-medium text-text-primary mb-1.5">
                                联系电话 <span class="text-red-500">*</span>
                            </label>
                            <input type="tel" id="contact-phone" name="contactPhone" required
                                   class="w-full px-3 py-2.5 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary transition-all"
                                   placeholder="请输入联系电话" pattern="^1[3-9]\d{9}$">
                        </div>
                        
                        <!-- 短信验证码 -->
                        <!-- <div>
                            <label class="block text-sm font-medium text-text-primary mb-1.5">
                                短信验证码 <span class="text-red-500">*</span>
                            </label>
                            <div class="flex gap-2">
                                <input type="text" id="sms-code" name="smsCode" required
                                       class="flex-1 px-3 py-2.5 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary transition-all"
                                       placeholder="请输入验证码" maxlength="6">
                                <button type="button" id="send-sms-btn" onclick="sendSmsCode()" 
                                        class="px-4 py-2.5 bg-primary text-white rounded-lg font-medium hover:bg-primary-dark transition-colors whitespace-nowrap text-sm">
                                    发送验证码
                                </button>
                            </div>
                        </div> -->
                    </form>
                    
                    <!-- 弹窗按钮 -->
                    <div class="flex gap-3 mt-6">
                        <button onclick="hideMerchantAuthModal()" 
                                class="flex-1 px-4 py-3 bg-gray-100 text-text-primary rounded-xl font-medium hover:bg-gray-200 transition-colors">
                            取消
                        </button>
                        <button id="submit-auth-btn" onclick="submitMerchantAuth()" 
                                class="flex-1 px-4 py-3 bg-primary text-white rounded-xl font-medium hover:bg-primary-dark transition-colors">
                            提交认证
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="../js/common.js"></script>
    <script src="../js/navigation.js"></script>
    <script src="../js/components.js"></script>
    <script src="../js/animate.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            Components.initComponents('my');
            CommonUtils.initButtonFeedback();
            
            // 初始化Token
            CommonUtils.initToken();
            
            // 检查登录状态并更新用户信息
            checkLoginStatus();
            
            // 初始化商户认证状态
            initMerchantAuthStatus();
            
            // 检查是否需要打开商户认证弹窗
            const openMerchantAuth = sessionStorage.getItem('openMerchantAuth');
            if (openMerchantAuth === 'true') {
                // 清除标记
                sessionStorage.removeItem('openMerchantAuth');
                
                // 延迟打开弹窗，确保页面已完全加载
                setTimeout(() => {
                    handleMerchantAuth();
                }, 500);
            }
        });
        
        // 检查登录状态
        async function checkLoginStatus() {
            const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true';
            const token = CommonUtils.getAccessToken();
            
            if (isLoggedIn && token) {
                try {
                    // 显示加载状态
                    showLoadingState();
                    
                    // 调用API获取最新用户信息
                    const result = await CommonUtils.getUserInfoAPI();
                    
                    if (result.data && result.data.user) {
                        const userInfo = result.data;
                        updateUserInfo(userInfo);
                        updateUserStats(userInfo);
                        
                        // 保存到localStorage
                        localStorage.setItem('currentUser', JSON.stringify(userInfo.user));
                    } else {
                        throw new Error('获取用户信息失败');
                    }
                } catch (error) {
                    console.error('获取用户信息失败:', error);
                    
                    // 如果Token失效，清除登录状态
                    if (error.message.includes('登录状态已过期')) {
                        localStorage.removeItem('isLoggedIn');
                        localStorage.removeItem('currentUser');
                        showLoginButton();
                    } else {
                        // 其他错误，尝试使用本地存储的信息
                        const localUserInfo = localStorage.getItem('currentUser');
                        if (localUserInfo) {
                            try {
                                const user = JSON.parse(localUserInfo);
                                updateUserInfo({ user: user });
                            } catch (e) {
                                showLoginButton();
                            }
                        } else {
                            showLoginButton();
                        }
                    }
                }
            } else {
                showLoginButton();
            }
        }
        
        // 更新已登录用户信息
        function updateUserInfo(userInfo) {
            const userNameEl = document.querySelector('.flex-1 h3');
            const userDescEl = document.querySelector('.flex-1 p');
            const loginBtnContainer = document.querySelector('.flex-1');
            const avatarImg = document.querySelector('.card-modern img');
            const logoutButton = document.getElementById('logout-button');
            
            if (userNameEl && userDescEl && loginBtnContainer) {
                const user = userInfo.user || userInfo;
                
                // 更新用户名 - 优先使用nickName，其次userName
                const displayName = user.nickName || user.userName || '用户';
                userNameEl.textContent = displayName;
                
                // 更新用户描述 - 显示手机号或角色信息
                let userDesc = '完善资料获取更多服务';
                if (user.phonenumber) {
                    userDesc = user.phonenumber;
                } else if (userInfo.roles && userInfo.roles.length > 0) {
                    userDesc = userInfo.roles.map(role => role.roleName || role.roleKey).join(', ');
                }
                userDescEl.textContent = userDesc;
                
                // 更新头像
                if (avatarImg && user.avatar) {
                    avatarImg.src = user.avatar;
                    avatarImg.alt = displayName;
                }
                
                // 移除登录按钮，添加编辑资料按钮
                const existingBtn = loginBtnContainer.querySelector('button');
                if (existingBtn) {
                    existingBtn.textContent = '编辑资料';
                    existingBtn.onclick = function() {
                        requireLogin(() => window.location.href = 'profile.html', '个人资料')();
                    };
                    existingBtn.classList.remove('gradient-primary');
                    existingBtn.classList.add('bg-gray-100', 'text-text-primary');
                }
                
                // 显示退出登录按钮
                if (logoutButton) {
                    logoutButton.style.display = 'flex';
                }
            }
        }
        
        // 更新用户统计数据
        function updateUserStats(userInfo) {
            // 这里可以根据实际API返回的数据更新统计信息
            // 目前使用模拟数据，后续可以调用相应的统计API
            
            const serviceCountEl = document.querySelector('.grid .text-xl:first-child');
            const demandCountEl = document.querySelector('.grid .text-xl:nth-child(2)');
            const favoriteCountEl = document.querySelector('.grid .text-xl:last-child');
            
            // 模拟统计数据，实际应该从API获取
            if (serviceCountEl) serviceCountEl.textContent = '0';
            if (demandCountEl) demandCountEl.textContent = '0';
            if (favoriteCountEl) favoriteCountEl.textContent = '0';
            
            // TODO: 调用统计API获取真实数据
            // loadUserStatistics(userInfo.user.userId);
        }
        
        // 显示加载状态
        function showLoadingState() {
            const userNameEl = document.querySelector('.flex-1 h3');
            const userDescEl = document.querySelector('.flex-1 p');
            
            if (userNameEl && userDescEl) {
                userNameEl.textContent = '加载中...';
                userDescEl.textContent = '正在获取用户信息';
            }
        }
        
        // 显示登录按钮（未登录状态）
        function showLoginButton() {
            const userNameEl = document.querySelector('.flex-1 h3');
            const userDescEl = document.querySelector('.flex-1 p');
            const loginBtnContainer = document.querySelector('.flex-1');
            const avatarImg = document.querySelector('.card-modern img');
            const logoutButton = document.getElementById('logout-button');
            
            if (userNameEl && userDescEl && loginBtnContainer) {
                userNameEl.textContent = '未登录';
                userDescEl.textContent = '完善资料获取更多服务';
                
                // 重置头像
                if (avatarImg) {
                    avatarImg.src = '/images/avatar.jpg';
                    avatarImg.alt = '用户头像';
                }
                
                const existingBtn = loginBtnContainer.querySelector('button');
                if (existingBtn) {
                    existingBtn.textContent = '立即登录';
                    existingBtn.onclick = function() {
                        window.location.href = 'login.html';
                    };
                    existingBtn.classList.add('gradient-primary');
                    existingBtn.classList.remove('bg-gray-100', 'text-text-primary');
                }
                
                // 隐藏退出登录按钮
                if (logoutButton) {
                    logoutButton.style.display = 'none';
                }
            }
        }
        
        // 加载用户统计数据（预留接口）
        async function loadUserStatistics(userId) {
            try {
                // TODO: 调用统计API
                // const stats = await CommonUtils.getUserStatsAPI(userId);
                // updateUserStatsDisplay(stats);
            } catch (error) {
                console.error('获取用户统计数据失败:', error);
            }
        }
        
        // 处理登出功能
        function handleLogout() {
            // 显示自定义确认弹窗
            showLogoutModal();
        }
        
        // 显示退出登录确认弹窗
        function showLogoutModal() {
            const modal = document.getElementById('logout-modal');
            const modalContent = document.getElementById('logout-modal-content');
            
            if (modal && modalContent) {
                modal.classList.remove('hidden');
                
                // 触发动画
                setTimeout(() => {
                    modalContent.classList.remove('scale-95', 'opacity-0');
                    modalContent.classList.add('scale-100', 'opacity-100');
                }, 10);
                
                // 阻止背景滚动
                document.body.style.overflow = 'hidden';
                
                // 添加点击背景关闭功能
                modal.onclick = function(e) {
                    if (e.target === modal) {
                        hideLogoutModal();
                    }
                };
            }
        }
        
        // 隐藏退出登录确认弹窗
        function hideLogoutModal() {
            const modal = document.getElementById('logout-modal');
            const modalContent = document.getElementById('logout-modal-content');
            
            if (modal && modalContent) {
                // 触发关闭动画
                modalContent.classList.remove('scale-100', 'opacity-100');
                modalContent.classList.add('scale-95', 'opacity-0');
                
                // 延迟隐藏
                setTimeout(() => {
                    modal.classList.add('hidden');
                    // 恢复背景滚动
                    document.body.style.overflow = '';
                }, 300);
            }
        }
        
        // 确认退出登录
        async function confirmLogout() {
            // 隐藏弹窗
            hideLogoutModal();
            
            try {
                // 显示加载状态
                CommonUtils.showToast('正在退出登录...', 'info');
                
                // 调用登出API
                await CommonUtils.logoutAPI();
                
                // 清除所有登录状态
                clearAllLoginData();
                
                // 显示成功提示
                CommonUtils.showToast('已安全退出登录', 'success');
                
                // 跳转到首页
                setTimeout(() => {
                    window.location.href = '../index.html';
                }, 1500);
                
            } catch (error) {
                console.error('登出失败:', error);
                
                // 即使API调用失败，也要清除本地数据
                clearAllLoginData();
                CommonUtils.showToast('已退出登录', 'success');
                
                // 跳转到首页
                setTimeout(() => {
                    window.location.href = '../index.html';
                }, 1500);
            }
        }
        
        // 清除所有登录数据
        function clearAllLoginData() {
            // 清除Token
            CommonUtils.clearAccessToken();
            
            // 清除用户信息
            localStorage.removeItem('currentUser');
            localStorage.removeItem('isLoggedIn');
            localStorage.removeItem('savedAccount');
            localStorage.removeItem('savedPassword');
            
            // 清除会话存储
            sessionStorage.clear();
        }
        
        // 检查登录状态
        function isLoggedIn() {
            const token = CommonUtils.getAccessToken();
            const isLoggedInFlag = localStorage.getItem('isLoggedIn') === 'true';
            return token && isLoggedInFlag;
        }
        
        // 需要登录的功能检查
        function checkLoginRequired(action, actionName) {
            if (!isLoggedIn()) {
                showLoginRequiredModal(actionName);
                return false;
            }
            return true;
        }
        
        // 显示需要登录的提示弹窗
        function showLoginRequiredModal(actionName) {
            const modal = document.createElement('div');
            modal.className = 'fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4';
            modal.innerHTML = `
                <div class="bg-white rounded-2xl shadow-2xl max-w-sm w-full mx-4 transform transition-all duration-300">
                    <div class="p-6">
                        <!-- 弹窗头部 -->
                        <div class="flex items-center justify-center mb-4">
                            <div class="w-16 h-16 rounded-full bg-primary/10 flex items-center justify-center">
                                <i class="fa fa-user-lock text-primary text-2xl"></i>
                            </div>
                        </div>
                        
                        <!-- 弹窗内容 -->
                        <div class="text-center mb-6">
                            <h3 class="text-lg font-bold text-text-primary mb-2">需要登录</h3>
                            <p class="text-sm text-text-secondary leading-relaxed">
                                使用"${actionName}"功能需要先登录账号，是否前往登录页面？
                            </p>
                        </div>
                        
                        <!-- 弹窗按钮 -->
                        <div class="flex gap-3">
                            <button onclick="hideLoginRequiredModal()" 
                                    class="flex-1 px-4 py-3 bg-gray-100 text-text-primary rounded-xl font-medium hover:bg-gray-200 transition-colors">
                                取消
                            </button>
                            <button onclick="goToLogin()" 
                                    class="flex-1 px-4 py-3 bg-primary text-white rounded-xl font-medium hover:bg-primary-dark transition-colors">
                                去登录
                            </button>
                        </div>
                    </div>
                </div>
            `;
            
            document.body.appendChild(modal);
            
            // 阻止背景滚动
            document.body.style.overflow = 'hidden';
            
            // 添加点击背景关闭功能
            modal.onclick = function(e) {
                if (e.target === modal) {
                    hideLoginRequiredModal();
                }
            };
        }
        
        // 隐藏登录提示弹窗
        function hideLoginRequiredModal() {
            const modal = document.querySelector('.fixed.inset-0.bg-black.bg-opacity-50.z-50');
            if (modal) {
                modal.remove();
                document.body.style.overflow = '';
            }
        }
        
        // 前往登录页面
        function goToLogin() {
            hideLoginRequiredModal();
            window.location.href = 'login.html';
        }
        
        // 需要登录的功能包装函数
        function requireLogin(action, actionName) {
            return function() {
                if (checkLoginRequired(action, actionName)) {
                    action();
                }
            };
        }
        
        // 头像相关变量
        let selectedAvatarFile = null;
        let currentAvatarUrl = '';
        
        // 商户认证相关变量
        let merchantAuthStatus = 'unverified'; // unverified, pending, verified, rejected
        let merchantAuthData = null; // 商户认证数据，用于表单回显
        let smsCountdown = 0;
        let smsTimer = null;
        
        // 处理头像点击事件
        function handleAvatarClick() {
            if (!isLoggedIn()) {
                showLoginRequiredModal('更换头像');
                return;
            }
            showAvatarUploadModal();
        }
        
        // 显示头像上传弹窗
        function showAvatarUploadModal() {
            const modal = document.getElementById('avatar-upload-modal');
            const modalContent = document.getElementById('avatar-upload-modal-content');
            const previewImg = document.getElementById('avatar-preview');
            const saveBtn = document.getElementById('save-avatar-btn');
            
            if (modal && modalContent) {
                // 重置状态
                selectedAvatarFile = null;
                saveBtn.disabled = true;
                
                // 设置当前头像为预览
                const currentAvatar = document.getElementById('user-avatar');
                if (currentAvatar) {
                    currentAvatarUrl = currentAvatar.src;
                    previewImg.src = currentAvatarUrl;
                }
                
                modal.classList.remove('hidden');
                
                // 触发动画
                setTimeout(() => {
                    modalContent.classList.remove('scale-95', 'opacity-0');
                    modalContent.classList.add('scale-100', 'opacity-100');
                }, 10);
                
                // 阻止背景滚动
                document.body.style.overflow = 'hidden';
                
                // 添加点击背景关闭功能
                modal.onclick = function(e) {
                    if (e.target === modal) {
                        hideAvatarUploadModal();
                    }
                };
            }
        }
        
        // 隐藏头像上传弹窗
        function hideAvatarUploadModal() {
            const modal = document.getElementById('avatar-upload-modal');
            const modalContent = document.getElementById('avatar-upload-modal-content');
            
            if (modal && modalContent) {
                // 触发关闭动画
                modalContent.classList.remove('scale-100', 'opacity-100');
                modalContent.classList.add('scale-95', 'opacity-0');
                
                // 延迟隐藏
                setTimeout(() => {
                    modal.classList.add('hidden');
                    // 恢复背景滚动
                    document.body.style.overflow = '';
                }, 300);
            }
        }
        
        // 处理头像文件选择
        function handleAvatarFileSelect(event) {
            const file = event.target.files[0];
            if (!file) return;
            
            // 验证文件类型
            if (!file.type.startsWith('image/')) {
                CommonUtils.showToast('请选择图片文件', 'error');
                return;
            }
            
            // 验证文件大小 (5MB)
            if (file.size > 5 * 1024 * 1024) {
                CommonUtils.showToast('图片大小不能超过5MB', 'error');
                return;
            }
            
            // 创建预览
            const reader = new FileReader();
            reader.onload = function(e) {
                const previewImg = document.getElementById('avatar-preview');
                const saveBtn = document.getElementById('save-avatar-btn');
                
                if (previewImg) {
                    previewImg.src = e.target.result;
                }
                
                if (saveBtn) {
                    saveBtn.disabled = false;
                }
                
                selectedAvatarFile = file;
            };
            
            reader.readAsDataURL(file);
        }
        
        // 保存头像
        async function saveAvatar() {
            if (!selectedAvatarFile) {
                CommonUtils.showToast('请先选择图片', 'warning');
                return;
            }
            
            const saveBtn = document.getElementById('save-avatar-btn');
            const hideLoading = CommonUtils.showLoading(saveBtn);
            
            try {
                // 上传头像文件
                CommonUtils.showToast('正在上传头像...', 'info');
                
                const uploadResult = await CommonUtils.uploadAvatarAPI(selectedAvatarFile);
                
                if (uploadResult.data && uploadResult.data.imgUrl) {
                    // 更新用户头像信息
                    await CommonUtils.updateUserAvatarAPI(uploadResult.data.imgUrl);
                    
                    // 更新页面显示
                    const userAvatar = document.getElementById('user-avatar');
                    if (userAvatar) {
                        userAvatar.src = uploadResult.data.imgUrl;
                    }
                    
                    // 更新本地存储的用户信息
                    const currentUser = localStorage.getItem('currentUser');
                    if (currentUser) {
                        try {
                            const userInfo = JSON.parse(currentUser);
                            userInfo.avatar = uploadResult.data.imgUrl;
                            localStorage.setItem('currentUser', JSON.stringify(userInfo));
                        } catch (e) {
                            console.warn('更新本地用户信息失败:', e);
                        }
                    }
                    
                    CommonUtils.showToast('头像更新成功', 'success');
                    hideAvatarUploadModal();
                } else {
                    throw new Error('上传失败，未返回头像URL');
                }
                
            } catch (error) {
                console.error('头像上传失败:', error);
                CommonUtils.showToast(error.message || '头像上传失败，请稍后重试', 'error');
            } finally {
                hideLoading();
            }
        }
        
        // 商户认证相关函数
        async function handleMerchantAuth() {
            if (!isLoggedIn()) {
                showLoginRequiredModal('商户认证');
                return;
            }
            
            // 根据认证状态显示不同内容
            switch (merchantAuthStatus) {
                case 'verified':
                    // 已审核，加载详情并支持修改
                    await loadMerchantDetailAndEdit();
                    break;
                case 'pending':
                    // 待审核，仅展示状态
                    showMerchantPendingModal();
                    break;
                case 'rejected':
                    // 驳回，允许重新提交
                    showMerchantAuthModal(true); // true 表示是重新提交
                    break;
                case 'unverified':
                default:
                    showMerchantAuthModal(false);
                    break;
            }
        }
        
        // 加载商户详情并支持修改
        async function loadMerchantDetailAndEdit() {
            try {
                showLoading('正在加载商户信息...');
                const result = await CommonUtils.getMyMerchantInfoAPI();
                
                if (result.code === 200 || result.code === 0) {
                    // 保存详情数据
                    merchantAuthData = result.data;
                    // 打开表单，模式为修改认证
                    await showMerchantAuthModal(false, true); // 第二个参数 true 表示是修改模式
                } else {
                    CommonUtils.showToast(result.msg || '获取商户信息失败', 'error');
                }
            } catch (error) {
                console.error('获取商户信息失败:', error);
                CommonUtils.showToast('获取商户信息失败，请稍后重试', 'error');
            } finally {
                hideLoading();
            }
        }
        
        // 显示待审核状态弹窗（不可编辑）
        function showMerchantPendingModal() {
            const modal = document.createElement('div');
            modal.className = 'fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4';
            modal.innerHTML = `
                <div class="bg-white rounded-2xl shadow-2xl max-w-sm w-full mx-4 transform transition-all duration-300">
                    <div class="p-6">
                        <!-- 图标 -->
                        <div class="mb-4 flex justify-center">
                            <div class="w-16 h-16 bg-yellow-100 rounded-full flex items-center justify-center">
                                <i class="fa fa-clock text-yellow-600 text-3xl"></i>
                            </div>
                        </div>
                        
                        <!-- 内容 -->
                        <div class="text-center mb-6">
                            <h3 class="text-lg font-bold text-text-primary mb-2">商户认证审核中</h3>
                            <p class="text-sm text-text-secondary leading-relaxed">
                                您的商户认证申请正在审核中，请勿重复提交。审核通过后即可使用完整功能，请耐心等待。
                            </p>
                        </div>
                        
                        <!-- 按钮 -->
                        <button onclick="this.closest('.fixed').remove(); document.body.style.overflow = '';" 
                                class="w-full px-4 py-3 bg-primary text-white rounded-xl font-medium hover:bg-primary-dark transition-colors">
                            我知道了
                        </button>
                    </div>
                </div>
            `;
            
            document.body.appendChild(modal);
            document.body.style.overflow = 'hidden';
            
            // 点击背景关闭
            modal.onclick = function(e) {
                if (e.target === modal) {
                    modal.remove();
                    document.body.style.overflow = '';
                }
            };
        }
        
        // 加载商户类型字典
        async function loadmerchantCategorys() {
            try {
                const result = await CommonUtils.getDictDataByTypeAPI('shfl');
                
                if (result.code === 200 && result.data && result.data.length > 0) {
                    const container = document.getElementById('merchant-type-container');
                    
                    // 清空容器
                    container.innerHTML = '';
                    
                    // 添加复选框选项
                    result.data.forEach(item => {
                        const checkboxWrapper = document.createElement('label');
                        checkboxWrapper.className = 'flex items-center gap-2 p-2 rounded-lg hover:bg-primary/5 cursor-pointer transition-colors';
                        
                        const checkbox = document.createElement('input');
                        checkbox.type = 'checkbox';
                        checkbox.name = 'merchantCategory';
                        checkbox.value = item.dictValue;
                        checkbox.className = 'w-4 h-4 text-primary border-gray-300 rounded focus:ring-primary focus:ring-2';
                        
                        const label = document.createElement('span');
                        label.className = 'text-sm text-text-primary';
                        label.textContent = item.dictLabel;
                        
                        checkboxWrapper.appendChild(checkbox);
                        checkboxWrapper.appendChild(label);
                        container.appendChild(checkboxWrapper);
                    });
                } else {
                    const container = document.getElementById('merchant-type-container');
                    container.innerHTML = '<p class="col-span-2 text-xs text-text-secondary text-center py-2">暂无商户类型数据</p>';
                }
            } catch (error) {
                console.error('加载商户类型失败:', error);
                CommonUtils.showToast('加载商户类型失败', 'error');
                const container = document.getElementById('merchant-type-container');
                container.innerHTML = '<p class="col-span-2 text-xs text-danger text-center py-2">加载失败，请稍后重试</p>';
            }
        }
        
        // 显示商户认证弹窗
        async function showMerchantAuthModal(isResubmit = false, isEditMode = false) {
            const modal = document.getElementById('merchant-auth-modal');
            const modalContent = document.getElementById('merchant-auth-modal-content');
            const authStatusInfo = document.getElementById('auth-status-info');
            const modalTitle = document.querySelector('#merchant-auth-modal h2');
            
            if (modal && modalContent) {
                // 加载商户类型字典
                await loadmerchantCategorys();
                
                // 重置表单
                document.getElementById('merchant-auth-form').reset();
                
                // 更新弹窗标题
                if (modalTitle) {
                    if (isEditMode) {
                        modalTitle.textContent = '修改商户认证';
                    } else if (isResubmit) {
                        modalTitle.textContent = '重新提交认证';
                    } else {
                        modalTitle.textContent = '商户认证';
                    }
                }
                
                // 根据状态更新提示信息
                if (isResubmit && authStatusInfo) {
                    authStatusInfo.className = 'mb-4 p-3 bg-red-50 rounded-xl border border-red-200';
                    const rejectReason = merchantAuthData?.rejectReason || merchantAuthData?.auditRemark || '认证申请已驳回';
                    authStatusInfo.innerHTML = `
                        <div class="flex items-start gap-2">
                            <i class="fa fa-exclamation-circle text-red-600 mt-0.5"></i>
                            <div class="flex-1">
                                <p class="text-sm text-red-800 font-medium mb-1">认证申请已驳回</p>
                                <p class="text-xs text-red-700">驳回原因：${rejectReason}</p>
                                <p class="text-xs text-red-700 mt-1">请修改后重新提交</p>
                            </div>
                        </div>
                    `;
                } else if (isEditMode && authStatusInfo) {
                    authStatusInfo.className = 'mb-4 p-3 bg-green-50 rounded-xl border border-green-200';
                    authStatusInfo.innerHTML = `
                        <div class="flex items-center gap-2">
                            <i class="fa fa-check-circle text-green-600"></i>
                            <p class="text-sm text-green-800">您的商户认证已通过，可以修改信息后重新提交审核</p>
                        </div>
                    `;
                } else if (authStatusInfo) {
                    authStatusInfo.className = 'mb-4 p-3 bg-blue-50 rounded-xl border border-blue-200';
                    authStatusInfo.innerHTML = `
                        <div class="flex items-center gap-2">
                            <i class="fa fa-info-circle text-blue-600"></i>
                            <p class="text-sm text-blue-800">请填写真实的商户信息，我们将进行审核</p>
                        </div>
                    `;
                }
                
                // 如果有数据，回显表单内容
                if (merchantAuthData && (isResubmit || isEditMode || merchantAuthStatus === 'pending')) {
                    fillMerchantAuthForm(merchantAuthData);
                }
                
                modal.classList.remove('hidden');
                
                // 触发动画
                setTimeout(() => {
                    modalContent.classList.remove('scale-95', 'opacity-0');
                    modalContent.classList.add('scale-100', 'opacity-100');
                }, 10);
                
                // 阻止背景滚动
                document.body.style.overflow = 'hidden';
                
                // 添加点击背景关闭功能
                modal.onclick = function(e) {
                    if (e.target === modal) {
                        hideMerchantAuthModal();
                    }
                };
            }
        }
        
        // 回显商户认证表单数据
        function fillMerchantAuthForm(data) {
            if (!data) return;
            
            // 回显商户名称
            if (data.merchantName || data.name) {
                const nameInput = document.getElementById('merchant-name');
                if (nameInput) nameInput.value = data.merchantName || data.name;
            }
            
            // 回显信用代码
            if (data.creditCode) {
                const creditCodeInput = document.getElementById('credit-code');
                if (creditCodeInput) creditCodeInput.value = data.creditCode;
            }
            
            // 回显联系人
            if (data.contactPerson || data.linkman) {
                const personInput = document.getElementById('contact-person');
                if (personInput) personInput.value = data.contactPerson || data.linkman;
            }
            
            // 回显联系电话
            if (data.contactPhone || data.phone) {
                const phoneInput = document.getElementById('contact-phone');
                if (phoneInput) phoneInput.value = data.contactPhone || data.phone;
            }
            
            // 回显商户类型（复选框）
            if (data.merchantCategory) {
                const categories = data.merchantCategory.split(',');
                categories.forEach(category => {
                    const checkbox = document.querySelector(`input[name="merchantCategory"][value="${category.trim()}"]`);
                    if (checkbox) checkbox.checked = true;
                });
            }
        }
        
        // 显示商户信息弹窗（已认证）
        function showMerchantInfoModal() {
            if (!merchantAuthData) {
                CommonUtils.showToast('无法获取商户信息', 'error');
                return;
            }
            
            const merchantName = merchantAuthData.merchantName || merchantAuthData.name || '未知';
            const creditCode = merchantAuthData.creditCode || '未提供';
            const contactPerson = merchantAuthData.contactPerson || merchantAuthData.linkman || '未提供';
            const contactPhone = merchantAuthData.contactPhone || merchantAuthData.phone || '未提供';
            
            // 解析商户类型
            let categoryNames = '未提供';
            if (merchantAuthData.merchantCategory) {
                categoryNames = merchantAuthData.merchantCategory;
            }
            
            const modal = document.createElement('div');
            modal.className = 'fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4';
            modal.innerHTML = `
                <div class="bg-white rounded-2xl shadow-2xl max-w-md w-full mx-4 transform transition-all duration-300">
                    <div class="p-6">
                        <!-- 弹窗头部 -->
                        <div class="flex items-center justify-between mb-4">
                            <h3 class="text-lg font-bold text-text-primary">商户信息</h3>
                            <button onclick="this.closest('.fixed').remove(); document.body.style.overflow = '';" class="w-8 h-8 rounded-full hover:bg-gray-100 flex items-center justify-center transition-colors">
                                <i class="fa fa-times text-gray-400"></i>
                            </button>
                        </div>
                        
                        <!-- 认证状态 -->
                        <div class="mb-4 p-3 bg-green-50 rounded-xl border border-green-200">
                            <div class="flex items-center gap-2">
                                <i class="fa fa-check-circle text-green-600"></i>
                                <p class="text-sm text-green-800 font-medium">商户认证已通过</p>
                            </div>
                        </div>
                        
                        <!-- 商户信息 -->
                        <div class="space-y-3">
                            <div class="flex items-start gap-3 p-3 bg-gray-50 rounded-lg">
                                <i class="fa fa-building text-primary mt-1"></i>
                                <div class="flex-1">
                                    <p class="text-xs text-text-secondary mb-1">商户名称</p>
                                    <p class="text-sm text-text-primary font-medium">${merchantName}</p>
                                </div>
                            </div>
                            
                            <div class="flex items-start gap-3 p-3 bg-gray-50 rounded-lg">
                                <i class="fa fa-id-card text-primary mt-1"></i>
                                <div class="flex-1">
                                    <p class="text-xs text-text-secondary mb-1">统一社会信用代码</p>
                                    <p class="text-sm text-text-primary font-medium">${creditCode}</p>
                                </div>
                            </div>
                            
                            <div class="flex items-start gap-3 p-3 bg-gray-50 rounded-lg">
                                <i class="fa fa-tag text-primary mt-1"></i>
                                <div class="flex-1">
                                    <p class="text-xs text-text-secondary mb-1">商户类型</p>
                                    <p class="text-sm text-text-primary font-medium">${categoryNames}</p>
                                </div>
                            </div>
                            
                            <div class="flex items-start gap-3 p-3 bg-gray-50 rounded-lg">
                                <i class="fa fa-user text-primary mt-1"></i>
                                <div class="flex-1">
                                    <p class="text-xs text-text-secondary mb-1">联系人</p>
                                    <p class="text-sm text-text-primary font-medium">${contactPerson}</p>
                                </div>
                            </div>
                            
                            <div class="flex items-start gap-3 p-3 bg-gray-50 rounded-lg">
                                <i class="fa fa-phone text-primary mt-1"></i>
                                <div class="flex-1">
                                    <p class="text-xs text-text-secondary mb-1">联系电话</p>
                                    <p class="text-sm text-text-primary font-medium">${contactPhone}</p>
                                </div>
                            </div>
                        </div>
                        
                        <!-- 关闭按钮 -->
                        <div class="mt-6">
                            <button onclick="this.closest('.fixed').remove(); document.body.style.overflow = '';" 
                                    class="w-full px-4 py-3 bg-primary text-white rounded-xl font-medium hover:bg-primary-dark transition-colors">
                                关闭
                            </button>
                        </div>
                    </div>
                </div>
            `;
            
            document.body.appendChild(modal);
            document.body.style.overflow = 'hidden';
            
            // 点击背景关闭
            modal.onclick = function(e) {
                if (e.target === modal) {
                    modal.remove();
                    document.body.style.overflow = '';
                }
            };
        }
        
        // 隐藏商户认证弹窗
        function hideMerchantAuthModal() {
            const modal = document.getElementById('merchant-auth-modal');
            const modalContent = document.getElementById('merchant-auth-modal-content');
            
            if (modal && modalContent) {
                // 触发关闭动画
                modalContent.classList.remove('scale-100', 'opacity-100');
                modalContent.classList.add('scale-95', 'opacity-0');
                
                // 延迟隐藏
                setTimeout(() => {
                    modal.classList.add('hidden');
                    // 恢复背景滚动
                    document.body.style.overflow = '';
                }, 300);
            }
        }
        
        // 发送短信验证码
        async function sendSmsCode() {
            const phoneInput = document.getElementById('contact-phone');
            const phone = phoneInput.value.trim();
            
            // 验证手机号
            const phoneRegex = /^1[3-9]\d{9}$/;
            if (!phone || !phoneRegex.test(phone)) {
                CommonUtils.showToast('请先输入正确的手机号码', 'error');
                phoneInput.focus();
                return;
            }
            
            const sendBtn = document.getElementById('send-sms-btn');
            const hideLoading = CommonUtils.showLoading(sendBtn);
            
            try {
                // 这里稍后替换为实际的API调用
                const result = await CommonUtils.sendSmsCodeAPI(phone);
                
                if (result.code === 200) {
                    CommonUtils.showToast('验证码已发送，请查收短信', 'success');
                    startSmsCountdown();
                } else {
                    throw new Error(result.msg || '发送失败');
                }
                
            } catch (error) {
                console.error('发送短信验证码失败:', error);
                CommonUtils.showToast(error.message || '发送失败，请稍后重试', 'error');
            } finally {
                hideLoading();
            }
        }
        
        // 开始短信倒计时
        function startSmsCountdown() {
            smsCountdown = 60;
            const sendBtn = document.getElementById('send-sms-btn');
            
            sendBtn.disabled = true;
            sendBtn.textContent = `${smsCountdown}秒后重发`;
            
            smsTimer = setInterval(() => {
                smsCountdown--;
                if (smsCountdown > 0) {
                    sendBtn.textContent = `${smsCountdown}秒后重发`;
                } else {
                    resetSmsButton();
                }
            }, 1000);
        }
        
        // 重置短信按钮
        function resetSmsButton() {
            const sendBtn = document.getElementById('send-sms-btn');
            if (sendBtn) {
                sendBtn.disabled = false;
                sendBtn.textContent = '发送验证码';
            }
            
            if (smsTimer) {
                clearInterval(smsTimer);
                smsTimer = null;
            }
            smsCountdown = 0;
        }
        
        // 提交商户认证
        async function submitMerchantAuth() {
            const form = document.getElementById('merchant-auth-form');
            
            // 获取所有选中的商户类型
            const selectedTypes = [];
            const checkboxes = document.querySelectorAll('input[name="merchantCategory"]:checked');
            checkboxes.forEach(checkbox => {
                selectedTypes.push(checkbox.value);
            });
            
            // 获取表单数据
            const authData = {
                merchantCategory: selectedTypes.join(','), // 将数组转换为逗号分隔的字符串
                merchantName: document.getElementById('merchant-name').value,
                creditCode: document.getElementById('credit-code').value,
                contactPerson: document.getElementById('contact-person').value,
                contactPhone: document.getElementById('contact-phone').value
            };
            
            // 表单验证
            if (!validateMerchantAuthForm(authData)) {
                return;
            }
            
            const submitBtn = document.getElementById('submit-auth-btn');
            const hideLoading = CommonUtils.showLoading(submitBtn);
            
            try {
                // 调用新增商户信息API
                const result = await CommonUtils.addMerchantInfoAPI(authData);
                
                if (result.code === 200 || result.code === 0) {
                    // 更新认证状态为审核中
                    merchantAuthStatus = 'pending';
                    merchantAuthData = authData;
                    
                    // 更新页面显示
                    updateMerchantAuthStatus('pending');
                    
                    // 保存到本地存储
                    localStorage.setItem('merchantAuthStatus', 'pending');
                    localStorage.setItem('merchantAuthData', JSON.stringify(authData));
                    
                    CommonUtils.showToast(result.msg || '商户认证申请已提交，请等待审核', 'success');
                    hideMerchantAuthModal();
                    
                    // 重新获取商户认证状态
                    setTimeout(() => {
                        initMerchantAuthStatus();
                    }, 1000);
                } else {
                    throw new Error(result.msg || '提交失败');
                }
                
            } catch (error) {
                console.error('商户认证提交失败:', error);
                CommonUtils.showToast(error.message || '提交失败，请稍后重试', 'error');
            } finally {
                hideLoading();
            }
        }
        
        // 验证商户认证表单
        function validateMerchantAuthForm(data) {
            // 商户类型验证（至少选择一个）
            if (!data.merchantCategory|| data.merchantCategory.length === 0) {
                CommonUtils.showToast('请至少选择一个商户类型', 'error');
                // 聚焦到商户类型容器
                const container = document.getElementById('merchant-type-container');
                if (container) {
                    container.scrollIntoView({ behavior: 'smooth', block: 'center' });
                    container.style.borderColor = '#ef4444';
                    setTimeout(() => {
                        container.style.borderColor = '';
                    }, 2000);
                }
                return false;
            }
            
            // 商户名称验证
            if (!data.merchantName || data.merchantName.trim().length < 2) {
                CommonUtils.showToast('请输入有效的商户名称', 'error');
                document.getElementById('merchant-name').focus();
                return false;
            }
            
            // 统一社会信用代码验证
            if (!data.creditCode || data.creditCode.trim().length === 0) {
                CommonUtils.showToast('请输入统一社会信用代码', 'error');
                document.getElementById('credit-code').focus();
                return false;
            }
            
            // 验证信用代码格式（18位，由数字和大写字母组成）
            const creditCodeRegex = /^[0-9A-HJ-NPQRTUWXY]{2}\d{6}[0-9A-HJ-NPQRTUWXY]{10}$/;
            if (!creditCodeRegex.test(data.creditCode.toUpperCase())) {
                CommonUtils.showToast('请输入正确的18位统一社会信用代码', 'error');
                document.getElementById('credit-code').focus();
                return false;
            }
            
            // 联系人验证
            if (!data.contactPerson || data.contactPerson.trim().length < 2) {
                CommonUtils.showToast('请输入有效的联系人姓名', 'error');
                document.getElementById('contact-person').focus();
                return false;
            }
            
            // 联系电话验证
            const phoneRegex = /^1[3-9]\d{9}$/;
            if (!data.contactPhone || !phoneRegex.test(data.contactPhone)) {
                CommonUtils.showToast('请输入有效的手机号码', 'error');
                document.getElementById('contact-phone').focus();
                return false;
            }
            
            // 短信验证码验证
            // if (!data.smsCode || data.smsCode.trim().length !== 6) {
            //     CommonUtils.showToast('请输入6位短信验证码', 'error');
            //     document.getElementById('sms-code').focus();
            //     return false;
            // }
            
            return true;
        }
        
        // 更新商户认证状态显示
        function updateMerchantAuthStatus(status, data) {
            const statusElement = document.getElementById('merchant-auth-status');
            const badgeElement = document.getElementById('merchant-auth-badge');
            
            if (!statusElement || !badgeElement) return;
            
            switch (status) {
                case 'verified':
                    // 显示商户名称或"已认证"
                    const merchantName = data?.merchantName || data?.name;
                    statusElement.textContent = merchantName ? merchantName : '已认证';
                    badgeElement.textContent = '已认证';
                    badgeElement.className = 'text-xs px-2 py-1 bg-green-100 text-green-600 rounded-full';
                    break;
                case 'pending':
                    statusElement.textContent = '待审核，请耐心等待';
                    badgeElement.textContent = '待审核';
                    badgeElement.className = 'text-xs px-2 py-1 bg-yellow-100 text-yellow-600 rounded-full';
                    break;
                case 'rejected':
                    // 显示驳回原因
                    const rejectReason = data?.rejectReason || data?.auditRemark || '认证申请已驳回';
                    statusElement.textContent = rejectReason;
                    badgeElement.textContent = '已驳回';
                    badgeElement.className = 'text-xs px-2 py-1 bg-red-100 text-red-600 rounded-full';
                    break;
                case 'unverified':
                default:
                    statusElement.textContent = '未认证';
                    badgeElement.textContent = '未认证';
                    badgeElement.className = 'text-xs px-2 py-1 bg-gray-100 text-gray-600 rounded-full';
                    break;
            }
        }
        
        // 初始化商户认证状态
        async function initMerchantAuthStatus() {
            // 检查是否已登录
            if (!isLoggedIn()) {
                updateMerchantAuthStatus('unverified', null);
                return;
            }
            
            try {
                // 调用API获取商户认证状态
                const result = await CommonUtils.checkIsMerchantAPI();
                
                if (result.code === 200 || result.code === 0) {
                    // 保存商户认证数据，用于表单回显
                    merchantAuthData = result.data || null;
                    
                    // 判断认证状态
                    // auditStatus: 0-已审核, 1-待审核, 2-驳回
                    const isMerchant = result.data?.isMerchant || false;
                    const auditStatus = result.data?.auditStatus;
                    let status = 'unverified';
                    
                    if (isMerchant || auditStatus === '0' || auditStatus === 0) {
                        status = 'verified'; // 已审核/已认证
                    } else if (auditStatus === '1' || auditStatus === 1) {
                        status = 'pending'; // 待审核
                    } else if (auditStatus === '2' || auditStatus === 2) {
                        status = 'rejected'; // 驳回
                    }
                    
                    merchantAuthStatus = status;
                    updateMerchantAuthStatus(status, result.data);
                } else {
                    // API返回错误，默认为未认证
                    merchantAuthStatus = 'unverified';
                    updateMerchantAuthStatus('unverified', null);
                }
            } catch (error) {
                console.error('获取商户认证状态失败:', error);
                // 发生错误，默认为未认证
                merchantAuthStatus = 'unverified';
                updateMerchantAuthStatus('unverified', null);
            }
        }
        
        // 我发布的服务（需要商户权限）
        async function handleMyServices() {
            const hasPermission = await CommonUtils.checkMerchantRequired(null, '我发布的服务');
            if (hasPermission) {
                window.location.href = 'my-posts.html?type=service';
            }
        }
        
        // 我发布的需求（需要商户权限）
        async function handleMyDemands() {
            const hasPermission = await CommonUtils.checkMerchantRequired(null, '我发布的需求');
            if (hasPermission) {
                window.location.href = 'my-posts.html?type=demand';
            }
        }
    </script>
</body>
</html>
